package 高频题;

public class 接雨水_42 {
    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int n = height.length;
        int left = 0;
        int right = n - 1;
        int res = 0;

        int l_max = height[0];
        int r_max = height[n - 1];

        while (left <= right) {
            //保持l_max是左指针经过的地方的最高的柱子
            l_max = Math.max(l_max, height[left]);
            r_max = Math.max(r_max, height[right]);

            if (l_max < r_max) {
                res = res + (l_max - height[left]);
                left++;
            } else {
                res = res + (r_max - height[right]);
                right--;
            }
        }
        return res;
    }
}
